package gui;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;

import toolkit.View;
import client.Client;

public class Frame extends JFrame
{
	private static Frame lastOpened;
	
	private static int openWindows = 0;
	
	public Frame()
	{
		setIconImage(View.getIcon());
		
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		
		addWindowListener(windowListener);
		
		// Close the window when escape is pressed.
		Action escapeAction = new AbstractAction()
		{
			public void actionPerformed(ActionEvent e)
			{
				closeWindow();
			}
		};
		
		KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
		
		getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
		getRootPane().getActionMap().put("ESCAPE", escapeAction);
	}
	
	public void center()
	{
		Dimension dimension = getToolkit().getScreenSize();
		Rectangle bounds = getBounds();
		setLocation((dimension.width - bounds.width) / 2, (dimension.height - bounds.height) / 2);
	}
	
	public static Frame getLastOpened()
	{
		return lastOpened;
	}
	
	private WindowListener windowListener = new WindowAdapter()
	{
		public void windowOpened(WindowEvent e)
		{
			openWindow();
		}
		
		public void windowClosing(WindowEvent e)
		{
			closeWindow();
		}
	};
	
	private void openWindow()
	{
		openWindows++;
		
		lastOpened = Frame.this;
	}
	
	private void closeWindow()
	{
		if (openWindows == 1)
		{
			Client.closeClient();
		}
		else
		{
			if (openWindows > 0)
			{
				openWindows--;
			}
			
			dispose();
		}
	}
}
